package com.browser.search;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import com.google.gson.Gson;
import com.google.gson.JsonArray;

@Data
public class SearchManager {
    private static final Logger logger = LoggerFactory.getLogger(SearchManager.class);
    private static final String SUGGESTION_URL = "https://suggestqueries.google.com/complete/search?client=firefox&q=%s";
    private final Gson gson;

    public SearchManager() {
        this.gson = new Gson();
    }

    public CompletableFuture<List<String>> getSuggestions(String query) {
        return CompletableFuture.supplyAsync(() -> {
            List<String> suggestions = new ArrayList<>();
            try {
                String encodedQuery = URLEncoder.encode(query, "UTF-8");
                URL url = new URL(String.format(SUGGESTION_URL, encodedQuery));
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept", "application/json");

                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    // 解析 Google 建议 API 的响应
                    JsonArray jsonArray = gson.fromJson(response.toString(), JsonArray.class);
                    JsonArray suggestionArray = jsonArray.get(1).getAsJsonArray();
                    
                    for (int i = 0; i < suggestionArray.size(); i++) {
                        suggestions.add(suggestionArray.get(i).getAsString());
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to get search suggestions for: {}", query, e);
            }
            return suggestions;
        });
    }

    public String getSearchUrl(String query) {
        try {
            String encodedQuery = URLEncoder.encode(query, "UTF-8");
            return "https://www.google.com/search?q=" + encodedQuery;
        } catch (Exception e) {
            logger.error("Failed to encode search query: {}", query, e);
            return "https://www.google.com";
        }
    }
} 